package com.sita.bluetactivity.Base;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import de.greenrobot.event.EventBus;

/**
 * Created by Jason on 2016/8/12.
 */
public class FileUtils {
    public static String SDPATH = Environment.getExternalStorageDirectory()
            + "/Photo_LJ/";
    private FileUtils fileUtils;
    private static Context context;

    public void getFileUtils(Context mContext){
        if (fileUtils==null){
            fileUtils = new FileUtils();
            fileUtils.context = mContext;
        }
    }

    public static String saveBitmap(Bitmap bm, String picName) {
        try {
            if (!isFileExist("")) {
                File tempf = createSDDir("");
            }
            File f = new File(SDPATH, picName + ".JPEG");
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            return f.getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static File createSDDir(String dirName) throws IOException {
        File dir = new File(SDPATH + dirName);
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {

            System.out.println("createSDDir:" + dir.getAbsolutePath());
            System.out.println("createSDDir:" + dir.mkdir());
        }
        return dir;
    }

    public static boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        file.isFile();
        return file.exists();
    }

    public static void delFile(String fileName) {
        File file = new File(SDPATH + fileName);
        if (file.isFile()) {
            file.delete();
        }
        file.exists();
    }

    public static void deleteDir() {
        File dir = new File(SDPATH);
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDir();
        }
        dir.delete();
    }

    public static boolean fileIsExists(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {

            return false;
        }
        return true;
    }

    public static void writeFile2SDCard(String CrashFilePath, String fileName, String sb) {
        File file = new File(CrashFilePath, fileName);
        try {
            FileWriter filerWriter = new FileWriter(file, true);//后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(sb);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String unzip(String filePath, String destination) {
        long starttime = System.currentTimeMillis();
        String jsonfile = "";
        try {
            FileInputStream inputStream = new FileInputStream(filePath);
            ZipInputStream zipStream = new ZipInputStream(inputStream);
            ZipEntry zEntry = null;
            while ((zEntry = zipStream.getNextEntry()) != null) {


                if (zEntry.isDirectory()) {
                    hanldeDirectory(zEntry.getName(), destination);
                } else {
                    jsonfile = destination + "/" + zEntry.getName();
                    FileOutputStream fout = new FileOutputStream(jsonfile);
                    BufferedOutputStream bufout = new BufferedOutputStream(fout);
                    byte[] buffer = new byte[1024];
                    int read = 0;
                    while ((read = zipStream.read(buffer)) != -1) {
                        bufout.write(buffer, 0, read);
                    }

                    zipStream.closeEntry();
                    bufout.close();
                    fout.close();
                }
            }
            zipStream.close();
           // LogUtils.d("Unzip", "Unzipping complete. path :  " + destination);
        } catch (Exception e) {
         //   LogUtils.d("Unzip", "Unzipping failed");
          //  e.printStackTrace();
        }

    //    LogUtils.i("Unzip", ">>>>cost time:" + String.valueOf(System.currentTimeMillis() - starttime) + "ms");
        return jsonfile;

    }

    public static void hanldeDirectory(String dir, String destination) {
        File f = new File(destination + dir);
        if (!f.isDirectory()) {
            f.mkdirs();
        }
    }

    public static class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... aurl) {
            int count;

            try {

                String fileUrl = aurl[0];
                String trackId = aurl[1];
                URL url = new URL(fileUrl);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                String destination = "/sdcard/";
                String zipfile = destination + fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(zipfile);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();

                String jsonFile = unzip(zipfile, destination);

                if (!TextUtils.isEmpty(jsonFile)) {
                    // delete the zip file
                    FileUtils.delFile(zipfile);
                    EventBus.getDefault().post(jsonFile);
                    // save data
              //      TracksInfoUtils.readTrackIntoLocalDB(trackId, jsonFile);

                    // reset the synced flag
                   // TracksInfoUtils.setTrackSynced(trackId);

                    //  delete the json file
//                    FileUtils.delFile(jsonFile);
                }
            } catch (Exception e) {
            }
            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC", progress[0]);
//            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
//            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
       //     TracksInfoUtils.decreaseCount();
            //if (TracksInfoUtils.getTrackCount() <= 0) {
            //    EventBus.getDefault().post(new TrackSyncedEvent());
         //   }
        }
    }




  /*  public static File storeRAWFilesToInternalStorage() {
        byte[] buffer = null;
        String DIR_NAME = "video/start";
        buffer = new byte[3000000];

       File mFilesDir = DaoSingleton.getInstance(context).getDaoSession().getFilesDir();
        File mImagesDir = new File(mFilesDir, DIR_NAME);

        if (!mImagesDir.exists() && !mImagesDir.isDirectory()) {
            boolean dirCreated = mImagesDir.mkdirs();
        }
        try {
            InputStream fileStream = context.getResources().openRawResource(R.raw.z3_start_video);
            fileStream.read(buffer);
            File fileWithinMyDir = new File(mImagesDir, "start.mp4");
            FileOutputStream outputStream = new FileOutputStream(fileWithinMyDir);

            outputStream.write(buffer);
            outputStream.close();
            return fileWithinMyDir;
        } catch (IOException e) {

        }
        return null;
    }
*/
}
